<template>
  <div class="address-management">
    <!-- 顶部搜索栏 -->
    <el-card class="search-card" shadow="hover">
      <div class="card-header">
        <h3 class="title">地址管理</h3>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-plus"
          @click="handleAdd"
          class="add-btn"
        >
          添加地址
        </el-button>
      </div>

      <el-row :gutter="20" class="search-row">
        <el-col :span="16">
          <input
            v-model="searchAddress"
            placeholder="搜索地址关键词"
            clearable
            @keyup.enter="fetchAddressList"
            prefix-icon="el-icon-search"
            class="search-input"
          />
        </el-col>
        <el-col :span="8">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click="fetchAddressList"
            class="search-btn"
          >
            搜索框
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 地址列表 -->
    <el-card class="list-card" shadow="hover">
      <el-table
        :data="addressList"
        border
        stripe
        highlight-current-row
        v-loading="loading"
        element-loading-text="加载中..."
        empty-text="暂无地址数据"
        class="address-table"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="userId" label="用户ID" align="center" />
        <el-table-column
          prop="userName"
          label="收货人"
          align="center"
          min-width="120"
        >
          <template #default="scope">
            <span class="address-text">{{ scope.row.userName || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="详细地址"
          align="center"
          min-width="200"
        >
          <template #default="scope">
            <div class="address-text">{{ scope.row.address }}</div>
          </template>
        </el-table-column>
        <el-table-column label="默认地址" align="center" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.isDefault === 1 ? 'success' : 'info'"
              effect="light"
              size="mini"
            >
              {{ scope.row.isDefault === 1 ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          min-width="160"
        >
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注信息"
          align="center"
          min-width="120"
        >
          <template #default="scope">
            <span class="remark-text">{{ scope.row.remark || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.isDel === 0 ? 'success' : 'danger'"
              effect="light"
              size="mini"
            >
              {{ scope.row.isDel === 0 ? "正常" : "已删除" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="140">
          <template #default="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
              class="operation-btn"
            >
              编辑
            </el-button>
            <el-button
              :type="parseInt(scope.row.isDel) === 0 ? 'danger' : 'success'"
              size="mini"
              :icon="
                scope.row.isDel === 0
                  ? 'el-icon-delete'
                  : 'el-icon-refresh-right'
              "
              @click="handleDelete(scope.row)"
              class="operation-btn"
            >
              {{ scope.row.isDel === 0 ? "删除" : "恢复" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          background
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      title="收货地址"
      :visible.sync="dialogFormVisible"
      width="550px"
      :before-close="handleClose"
      class="address-dialog"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="formRules"
        label-width="90px"
        class="address-form"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input
            v-model="form.userId"
            placeholder="请输入用户ID"
            type="number"
            :disabled="form.id !== null"
          />
        </el-form-item>

        <el-form-item label="收货人" prop="userName">
          <!-- 改为userName -->
          <el-input v-model="form.userName" placeholder="请输入收货人姓名" />
        </el-form-item>

        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" />
        </el-form-item>

        <!-- 限制选择到区 -->
        <el-form-item label="所在地区" prop="selectedAddress">
          <el-cascader
            ref="cascader"
            v-model="selectedAddress"
            :options="convertedCascaderOptions"
            @change="handleAddressChange"
          >
          </el-cascader>
        </el-form-item>

        <el-form-item label="详细地址" prop="detailAddress">
          <el-input
            v-model="form.detailAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入街道、门牌号、小区、楼栋号、单元等详细地址信息"
          />
        </el-form-item>

        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="选填：添加备注信息（如丈母娘家、兄弟家、姐妹家等）"
          />
        </el-form-item>

        <el-form-item label="设为默认" prop="isDefault">
          <el-switch
            v-model="form.isDefault"
            active-value="1"
            inactive-value="0"
            active-color="#ff4400"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false" class="cancel-btn">
            取消
          </el-button>
          <el-button type="primary" @click="submitForm" class="confirm-btn">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 引入省市区JSON数据
import areaData from "@/assets/data/address.json";

export default {
  data() {
    return {
      addressList: [],
      pageNum: 1,
      pageSize: 10,
      totalCount: 0,
      searchAddress: "",
      dialogFormVisible: false,
      selectedAddress: [],
      convertedCascaderOptions: [],
      form: {
        id: null,
        userId: "",
        userName: "", // 改为userName
        provinceCode: "",
        cityCode: "",
        districtCode: "",
        provinceName: "",
        cityName: "",
        districtName: "",
        detailAddress: "",
        address: "",
        isDefault: 0,
        remark: "",
        isDel: 0,
      },
      formRules: {
        userId: [{ required: true, message: "请输入用户ID", trigger: "blur" }],
        userName: [
          // 改为userName
          { required: true, message: "请输入收货人姓名", trigger: "blur" },
        ],
        selectedAddress: [
          {
            message: "请选择所在地区",
            trigger: "change",
          },
        ],
        detailAddress: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
          { min: 5, message: "详细地址至少5个字符", trigger: "blur" },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号码格式不正确",
            trigger: "blur",
          },
        ],
      },
      loading: false,
    };
  },
  mounted() {
    this.fetchAddressList();
    this.initAreaData();
  },
  methods: {
    // 初始化地区数据
    initAreaData() {
      this.convertedCascaderOptions = this.convertToCascaderArray(areaData);
    },
    // 递归转换函数：对象转数组
    convertToCascaderArray(obj) {
      return Object.entries(obj).map(([code, item]) => {
        let temp = {
          label: item.n,
          value: item.n,
        };

        let children =
          item.c && this.isThirdLevel(item.c)
            ? []
            : item.c
            ? this.convertToCascaderArray(item.c)
            : [];

        if (children.length > 0) {
          temp.children = children;
        }

        return temp;
      });
    },
    isThirdLevel(subObj) {
      const subKeys = Object.keys(subObj);
      if (subKeys.length === 0) return false;
      const firstSubItem = subObj[subKeys[0]];
      return firstSubItem.c && Object.keys(firstSubItem.c).length === 0;
    },
    // 处理地区选择变化
    handleAddressChange(value) {
      if (value && value.length === 3) {
        const [provinceCode, cityCode, districtCode] = value;

        // 查找选中的省市区名称
        const provinceObj = this.convertedCascaderOptions.find(
          (item) => item.value === provinceCode
        );
        const provinceName = provinceObj?.label || "";
        const cityObj = provinceObj?.children.find(
          (item) => item.value === cityCode
        );
        const cityName = cityObj?.label || "";
        const districtObj = cityObj?.children.find(
          (item) => item.value === districtCode
        );
        const districtName = districtObj?.label || "";

        // 更新表单数据
        this.form.provinceCode = provinceCode;
        this.form.cityCode = cityCode;
        this.form.districtCode = districtCode;
        this.form.provinceName = provinceName;
        this.form.cityName = cityName;
        this.form.districtName = districtName;
        console.log(
          "省：" +
            this.form.provinceName +
            " 市：" +
            this.form.cityName +
            " 区：" +
            this.form.districtName
        );
      }
    },
    // 获取地址列表
    async fetchAddressList() {
      this.loading = true;
      try {
        const response = await this.$axios.get("/easybuy/address/showAddress", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchAddress: this.searchAddress,
          },
        });

        if (response.status === 200 && response.data.code === "200") {
          this.addressList = response.data.info.list || [];
          this.totalCount = response.data.info.total || 0;
        } else {
          this.$message.error(response.data.message || "获取地址列表失败");
        }
      } catch (error) {
        console.error("网络请求错误:", error);
        this.$message.error("网络错误，请稍后重试");
      } finally {
        this.loading = false;
      }
    },
    // 分页相关
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchAddressList();
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.fetchAddressList();
    },
    // 添加地址
    handleAdd() {
      console.log("handleAdd 被触发");
      this.resetForm();

      this.dialogFormVisible = true;
      console.log("dialogFormVisible检查是否为true:", this.dialogFormVisible);
    },
    // 编辑地址
    handleEdit(row) {
      this.resetForm();
      this.form = { ...row }; // 自动回显userName

      this.form.isDel = 0;
      this.form.isDefault = row.isDefault || 0; // 保持原有默认状态

      // 处理级联选择器回显（使用code而非name）
      if (row.provinceCode && row.cityCode && row.districtCode) {
        this.selectedAddress = [
          row.provinceCode,
          row.cityCode,
          row.districtCode,
        ];
        this.$nextTick(() => {
          this.$refs.cascader?.handleUpdate(this.selectedAddress);
        });
      }

      this.dialogFormVisible = true;
    },
    // 删除/恢复地址
    async handleDelete(row) {
      const action = row.isDel === 0 ? "删除" : "恢复";
      const url =
        action === "删除"
          ? "/easybuy/address/deleteAddress"
          : "/easybuy/address/returnAddress";

      this.$confirm(`确定要${action}该地址吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const response = await this.$axios.post(url, null, {
              params: { id: row.id },
            });

            if (response.data.code === "200") {
              this.$message.success(`${action}成功`);
              this.fetchAddressList();
            } else {
              this.$message.error(response.data.message || `${action}失败`);
            }
          } catch (error) {
            console.error(`${action}地址错误`, error);
            this.$message.error("网络错误，请稍后重试");
          }
        })
        .catch(() => {});
    },
    // 提交表单
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;

        try {
          // 更新完整地址
          this.form.address = `${this.form.provinceName}省${this.form.cityName}市${this.form.districtName}区${this.form.detailAddress}`;
          console.log("准备提交的地址：" + this.form.address);
          let response;

          if (this.form.id) {
            // 更新操作
            response = await this.$axios.post(
              "/easybuy/address/updateAddress",
              this.form
            );
          } else {
            // 新增操作
            response = await this.$axios.post(
              "/easybuy/address/insertAddress",
              this.form
            );
          }

          if (response.data.code === "200") {
            this.$message.success(this.form.id ? "更新成功" : "新增成功");
            this.dialogFormVisible = false;
            this.fetchAddressList();
          } else {
            this.$message.error(
              response.data.message || (this.form.id ? "更新失败" : "新增失败")
            );
          }
        } catch (error) {
          console.error(this.form.id ? "更新地址错误" : "新增地址错误", error);
          this.$message.error("网络错误，请稍后重试");
        }
      });
    },
    // 重置表单
    resetForm() {
      this.form = {
        id: null,
        userId: "",
        userName: "", // 改为userName
        provinceCode: "",
        cityCode: "",
        districtCode: "",
        provinceName: "",
        cityName: "",
        districtName: "",
        detailAddress: "",
        address: "",
        isDefault: 0,
        remark: "",
        isDel: 0,
      };
      this.selectedAddress = [];

      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return "";
      const date = new Date(timestamp);
      return date.toLocaleString();
    },
    // 关闭对话框
    handleClose(done) {
      this.resetForm();
      done();
    },
  },
};
</script>

<style scoped>
/* 整体布局 */
.address-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 搜索给定资料 */
.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.search-row {
  padding: 15px 0;
}

.search-input {
  width: 100%;
}

.search-btn {
  width: 100%;
}

.add-btn {
  display: flex;
  align-items: center;
}

/* 列表给定资料 */
.list-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.address-table {
  margin-top: 10px;
}

.address-text {
  max-width: 200px;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.remark-text {
  color: #606266;
}

.operation-btn {
  margin-right: 3px;
  padding: 5px 8px;
}

/* 分页 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.show {
  display: block;
}
/* 对话框 */
.address-dialog .el-dialog__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
}

.address-dialog .el-dialog__title {
  font-size: 16px;
  font-weight: 500;
}

.address-form {
  padding: 15px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>